import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-05-07
 * Time: 16:29
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap(){
        this.elem = new int[10];
    }

    public void createHeap(int[] array) {
        for(int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for(int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent --) {
            shiftDown(parent, usedSize);
        }
    }

    private void shiftDown(int parent, int len) {      //向下调整

        int child = 2 * parent + 1;

        while(child < len) {

            if(child + 1 < len && elem[child] < elem[child + 1]) {
                child = child + 1;
            }

            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }

        }
    }

    public void push(int val) {
        //检查满
        if(isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }

        //2.存数据
        elem[usedSize] = val;
        usedSize ++;
        shiftUp(usedSize - 1);
    }
    public boolean isFull() {
        return usedSize == elem.length;
    }
    public void shiftUp(int child) {          //向上调整
        int parent = (child - 1) / 2;
        while(child > 0) {
            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public void poll() {
        if(empty()) {
            throw new HeapEmptyException("优先级对队列是空的！");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize - 1];
        elem[usedSize - 1] = tmp;
        usedSize --;

        shiftDown(0, usedSize);
    }

    public boolean empty() {
        return usedSize == 0;
    }
    public int peek() {
        if(empty()) {
            throw new HeapEmptyException("优先级队列是空的！");
        }
        return elem[0];
    }

    /**
     * 堆排序
     * 升序：建大堆
     * 降序：建小堆
     * 1.建立大根堆:  O(n)
     * 2.N*logN
     */
    public void HeapSort() {
        int end = usedSize - 1;
        while(end > 0) {
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0, end);
            end --;
        }
    }

}
